﻿
<#
 .DESCRIPTION
  This module contains cmdlet to help writing Powershell scripts against Team
  Foundation Server.
  
 .NOTES
  Copyright © Microsoft Corporation. All Rights Reserved.
  This code released under the terms of the 
  Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
  This is sample code only, do not use in production environments
#>




# load the TFS.psm1 PowerShell module located in the same location as this script.
$ScriptDirectory = Split-Path $MyInvocation.MyCommand.Path
Import-Module (Join-Path $ScriptDirectory TFS.psm1)

function Clone-WorkItemType 
{
param (
	[psobject] $SourceProject,
	[psobject] $DestinationProject,
	[string] $WorkItemTypeName,
	[Switch] $includeGlobalLists
)
	# get the work item type xml from the source project.
	$WorkItemType = $SourceProject.WorkItemTypes[$WorkItemTypeName]
	$sourceXml = $WorkItemType.Export($includeGlobalLists)
	$definition = $sourceXml.InnerXml
	
	try
	{		
		# verify against target, may raise an exception
		[Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType]::Validate($DestinationProject, $definition)
		
		# import the work item type definition xml into the destination project
		# if no exceptions, then clone was successfull.
		$DestinationProject.WorkItemTypes.Import($definition)
		Write-Host "Clone succeeded."
	}
	catch [System.Xml.XmlException]
	{
		Write-Error "Xml Exception: \n\n$($_.Message)"
	}
	catch [System.Xml.Schema.XmlSchemaValidationException]
	{
		Write-Error "Xml Schema Validation Exception: \n\n$($_.Message)"
	}
}

# source and target tfs project collections and team projects
$sourceCollectionName = "DefaultCollection"
$sourceProjectName = "PlaygroundAgile50"
$destinationCollectionName = "DefaultCollection"
$destinationProjectName = "RangersDemo"

# connect to TFS
$tfs = Get-Tfs "http://$env:COMPUTERNAME`:8080/tfs"

# create connection to both source and target team projects
$sourceCollection = ($tfs |  Get-TfsCollection -Name $sourceCollectionName)
$sourceProject = $sourceCollection.WIT.Projects[$sourceProjectName]

$destinationCollection = ($tfs |  Get-TfsCollection -Name $destinationCollectionName)
$destinationProject = $destinationCollection.WIT.Projects[$destinationProjectName]

# call the clone work item type function 
Clone-WorkItemType `
	-SourceProject $sourceProject `
	-DestinationProject $destinationProject `
	-WorkItemTypeName "Bug"